<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table border stripe :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index === 0 ? 'bdtop' : 'bdbottom', 'vcenter']"
              v-for="(item,index) in scope.row.children"
              :key="item.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二、三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2,index2) in item.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialogVisible(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRolesById(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="50%"
      @close="rolesDialogClosed"
    >
      <el-form ref="rolesFormRef" :model="addRoles" label-width="80px" :rules="addFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户弹框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialogVisible"
      width="50%"
      @close="rolesDialogClosed"
    >
      <el-form ref="rolesFormRef" :model="editRoles" label-width="80px" :rules="addFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="setRightDialogVisible" width="30%" @close="setDialogClose">
      <el-tree ref="treeRef" :data="rightsList" :props="rightTreetProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 权限用户数据
      rolesList: [],
      //   控制添加角色弹框的显示
      addRolesDialogVisible: false,
      // 控制编辑角色弹框的显示
      editRolesDialogVisible: false,
      //   添加角色表单数据
      addRoles: {
        roleName: '',
        roleDesc: ''
      },
      //   添加角色表单验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      //   编辑角色表单数据
      editRoles: {},
      // 所有权限列表数据
      rightsList: [],
      // 控制分配权限对话框的显示
      setRightDialogVisible: false,
      // 树形控件的属性绑定对象
      rightTreetProps: {
        label: 'authName',
        children: 'children'
      },
      // 树状结构默认选中的数据
      defKeys: [],
      // 当前即将分配角色的id
      roleId: ''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$axios.get('roles');
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败');
      }
      this.rolesList = res.data;
      //   console.log(this.rolesList);
    },
    // 关闭弹框时触发
    rolesDialogClosed() {
      this.$refs.rolesFormRef.resetFields();
    },
    // 添加角色信息
    addRolesInfo() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$axios.post('roles', this.addRoles);
        if (res.meta.status !== 201) return this.$message.error('添加角色失败');
        this.$message.success('添加角色成功');
        this.addRolesDialogVisible = false;
        this.getRolesList();
      });
    },
    // 查询修改角色的信息
    async editDialogVisible(id) {
      const { data: res } = await this.$axios.get('roles/' + id);
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败');
      }
      this.editRoles = res.data;
      this.editRolesDialogVisible = true;
    },
    // 修改角色信息
    editRolesInfo() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$axios.put(
          'roles/' + this.editRoles.roleId,
          {
            id: this.editRoles.roleId,
            roleName: this.editRoles.roleName,
            roleDesc: this.editRoles.roleDesc
          }
        );
        if (res.meta.status !== 200) {
          this.$message.error('修改失败');
        }
        this.editRolesDialogVisible = false;
        this.getRolesList();
        this.$message.success('修改成功');
      });
    },
    // 删除角色
    removeRolesById(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$axios.delete('roles/' + id);
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
          this.getRolesList();
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 删除指定权限
    removeRightById(role, rightId) {
      // 弹框确认
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$axios.delete(
            'roles/' + role.id + '/rights/' + rightId
          );
          if (res.meta.status === 200) {
            // console.log(role.id);
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }
          role.children = res.data;
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 显示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id;
      const { data: res } = await this.$axios.get('rights/tree');
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败');
      }
      this.rightsList = res.data;
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true;
    },
    // 获取角色下所有三级权限的id并保存在defKeys数组中
    getLeafKeys(node, arr) {
      // 若node.children为false，则表示已经是第三级
      if (!node.children) {
        return arr.push(node.id);
      }
      // 如果不是第三季，则利用递归遍历
      node.children.forEach(item => {
        return this.getLeafKeys(item, arr);
      });
    },
    // 关闭分配权限对话框触发
    setDialogClose() {
      this.defKeys = [];
    },
    // 确定为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(',');
      const { data: res } = await this.$axios.post('roles/' + this.roleId + '/rights', {
        rids: idStr
      });
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败');
      }
      this.$message.success('分配权限成功');
      this.getRolesList();
      this.setRightDialogVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
